/****************************************************************************
 * Copyright (C) 2013 Dj_Skual
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************/
#include "GetSaveListTask.hpp"
#include "../../Network/networkops.h"
#include "../../Controls/Application.h"

GetSaveListTask::GetSaveListTask(std::string ID)
	: ManageProgressWindow(tr("Downloading saveslist:"), "www.wiisave.com", false)
	, id(ID)
{
	ThreadedTaskHandler::Instance()->AddTask(this);
}

void GetSaveListTask::Execute(void)
{
	WiiSave_List * SaveList = NULL;
	std::string region;
	int result = 1;
	
	//! Generate gameUrl
	std::string WiiSaveListURL("http://wiisave.com/savegamecode_xml.php?gamecode=");
	WiiSaveListURL += id.substr(0, 3);
	
	//! Check Connection
	if(!CheckConnection(WiiSaveListURL.c_str()))
	{
		result = -3;
		goto end;
	}
	
	//! Check Region
	switch (id[3])
	{
		case 'E':
			region = "E - USA / Canada";
			break;
		case 'J':
			region = "J - Japanese";
			break;
		case 'W':
			region = "J - Japanese";//region = "NTSC T";
			break;
		case 'K':
			region = "J - Japanese";//region = "NTSC K";
			break;
		default:
		case 'P':
		case 'D':
		case 'F':
		case 'I':
		case 'S':
		case 'H':
		case 'U':
		case 'X':
		case 'Y':
		case 'Z':
			region = "P - European / Other / PAL";
			break;
	}
	
	//! Get list
	SaveList = new WiiSave_List(WiiSaveListURL);

	if (!SaveList->GetCount())
	{
		delete SaveList;
		SaveList = NULL;
		result = -4;
		goto end;
	}
	
	if (!SaveList->FilterList(region))
	{
		delete SaveList;
		SaveList = NULL;
		result = -5;
	}
	
  end:
	TaskEnd(SaveList, result);
	
	Application::Instance()->PushForDelete(this);
}
